import { useState, useEffect } from 'react'
import Taro, { getCurrentInstance, useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import { View, Text, Image, ScrollView, Button } from '@tarojs/components'
import { Empty, Loading } from '@taroify/core'
import { ArrowLeft, LikeOutlined, Like, ShareOutlined } from '@taroify/icons'
import recipeService from '../utils/recipeService'
import './detail.scss'

const RecipeDetail = () => {
  const [recipe, setRecipe] = useState(null)
  const [isLiked, setIsLiked] = useState(false)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useShareAppMessage(() => {
    if (recipe) {
      return {
        title: `🍳 今天做了${recipe.name}，超好吃！`,
        path: `/pages-recipe/detail?id=${recipe.id}`,
        imageUrl: recipe.image
      }
    }
    return {
      title: '🍽️ 发现超多美味菜谱，快来一起学做菜！',
      path: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-cai-bg.jpg'
    }
  })

  // 添加朋友圈分享
  useShareTimeline(() => {
    if (recipe) {
      return {
        title: `🍳 今天做了${recipe.name}，超级美味，快来看看做法吧！`,
        path: `/pages-recipe/detail?id=${recipe.id}`,
        imageUrl: recipe.image
      }
    }
    return {
      title: '🍽️ 发现超多美味菜谱，快来一起学做菜！',
      path: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-cai-bg.jpg'
    }
  })

  // 获取页面参数
  useEffect(() => {
    const fetchRecipeDetail = async () => {
      const params = getCurrentInstance().router.params

      if (params.id) {
        try {
          setLoading(true)

          // 从云端获取食谱数据
          const recipeData = await recipeService.getRecipes()
          const recipeId = parseInt(params.id, 10)
          const foundRecipe = recipeData.find((item) => item.id === recipeId)

          if (foundRecipe) {
            setRecipe(foundRecipe)

            // 检查是否已收藏
            try {
              const likedRecipes = Taro.getStorageSync('likedRecipes') || []
              if (likedRecipes.includes(recipeId)) {
                setIsLiked(true)
              }
            } catch (err) {
              console.error('获取收藏状态出错:', err)
            }
          } else {
            setError('未找到该菜谱')
          }
        } catch (err) {
          console.error('获取菜谱详情失败:', err)
          setError('加载失败，请重试')
          Taro.showToast({
            title: '加载失败，请重试',
            icon: 'none'
          })
        } finally {
          setLoading(false)
        }
      } else {
        setError('缺少菜谱ID')
        setLoading(false)
      }
    }

    fetchRecipeDetail()
  }, [])

  // 返回上一页
  const goBack = () => {
    // 获取页面栈
    const pages = Taro.getCurrentPages()
    // 如果只有一个页面（说明是从分享直接进入的首页）
    if (pages.length <= 1) {
      // 跳转到菜谱首页而不是使用navigateBack
      Taro.redirectTo({
        url: '/pages-recipe/index'
      })
    } else {
      Taro.navigateBack()
    }
  }

  // 收藏/取消收藏
  const toggleLike = () => {
    try {
      const recipeId = recipe.id
      let likedRecipes = Taro.getStorageSync('likedRecipes') || []

      if (isLiked) {
        // 取消收藏
        likedRecipes = likedRecipes.filter((id) => id !== recipeId)
      } else {
        // 添加收藏
        likedRecipes.push(recipeId)
      }

      Taro.setStorageSync('likedRecipes', likedRecipes)
      setIsLiked(!isLiked)

      Taro.showToast({
        title: isLiked ? '已取消收藏' : '已收藏',
        icon: 'success',
        duration: 1500
      })
    } catch (error) {
      console.error('收藏操作失败:', error)
    }
  }

  // 分享菜谱
  const handleShare = () => {
    if (process.env.TARO_ENV === 'weapp') {
      // 微信小程序环境下，调用分享功能
      Taro.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    } else {
      // 其他环境下，模拟分享功能
      Taro.showToast({
        title: '分享功能在当前环境不可用',
        icon: 'none'
      })
    }
  }

  // 如果正在加载
  if (loading) {
    return (
      <View className='loading-container'>
        <Loading type='spinner' />
        <Text className='loading-text'>加载中...</Text>
      </View>
    )
  }

  // 如果有错误或无菜谱数据
  if (error || !recipe) {
    return (
      <View className='recipe-not-found'>
        <Empty>
          <Empty.Image />
          <Empty.Description>{error || '未找到该菜谱'}</Empty.Description>
          <Button className='back-btn' color='primary' size='small' onClick={goBack}>
            返回
          </Button>
        </Empty>
      </View>
    )
  }

  return (
    <View className='detail-page'>
      {/* 顶部图片区域 */}
      <View className='recipe-header'>
        <Image className='recipe-image' src={recipe.image} mode='aspectFill' />
        <View className='header-overlay'>
          <View className='back-btn' onClick={goBack}>
            <ArrowLeft size='20' />
          </View>
          <Text className='recipe-name'>{recipe.name}</Text>
          <View className='recipe-tags'>
            {recipe.tags.map((tag, index) => (
              <Text key={index} className='tag'>
                {tag}
              </Text>
            ))}
            {recipe.isVegetarian && <Text className='tag vegetarian'>素食</Text>}
          </View>
        </View>
      </View>

      {/* 内容区域 */}
      <ScrollView scrollY className='recipe-content'>
        {/* 操作按钮 */}
        <View className='action-buttons'>
          <View className='action-btn like-btn' onClick={toggleLike}>
            {isLiked ? <Like color='#ff6b6b' size='22' /> : <LikeOutlined size='22' />}
            <Text className='btn-text'>{isLiked ? '已收藏' : '收藏'}</Text>
          </View>
          <Button className='action-btn share-btn' openType='share'>
            <ShareOutlined size='22' />
            <Text className='btn-text'>分享</Text>
          </Button>
        </View>

        {/* 食材部分 */}
        <View className='section ingredients-section'>
          <Text className='section-title'>食材准备</Text>
          <View className='ingredients-list'>
            {recipe.ingredients.map((ingredient, index) => (
              <View key={index} className='ingredient-item'>
                <View className='ingredient-dot' />
                <Text className='ingredient-name'>{ingredient}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* 烹饪步骤 */}
        <View className='section steps-section'>
          <Text className='section-title'>烹饪步骤</Text>
          <View className='steps-list'>
            {recipe.steps.map((step, index) => (
              <View key={index} className='step-item'>
                <View className='step-number'>
                  <Text>{index + 1}</Text>
                </View>
                <View className='step-content'>
                  <Text className='step-description'>{step.text}</Text>
                  {step.img && <Image className='step-image' src={step.img} mode='widthFix' />}
                </View>
              </View>
            ))}
          </View>
        </View>

        {/* 小贴士 */}
        <View className='section tips-section'>
          <Text className='section-title'>烹饪小贴士</Text>
          <Text className='tips-content'>
            {recipe.name.includes('鱼')
              ? '鱼类烹饪前最好先用盐水浸泡去腥，掌握火候可保持鲜嫩口感。'
              : recipe.isVegetarian
                ? '蔬菜翻炒时间不宜过长，可保持营养和清脆口感。'
                : '肉类食材最好提前入味，炒制前最好沥干水分以便更好地上色。'}
          </Text>
        </View>
      </ScrollView>
    </View>
  )
}

export default RecipeDetail
